package org.iabako.server.taglib;

import org.iabako.shared.entity.enumeration.Language;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by jose on 09/10/14.
 */
public class MessagesTag extends AbstractTag {

    public int doStartTag() throws JspException {

        JspWriter out = pageContext.getOut();

        Language pickedLang = getPickedLanguage((HttpServletRequest) pageContext.getRequest());
        String msgFilePrefix = "/org/iabako/i18n/";

        InputStream is = this.getClass().getResourceAsStream(msgFilePrefix + pickedLang.getMessagesFileName());
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            String line;
            int count = 0;
            out.println("<meta name=\"gwt:property\" content=\"locale=" + pickedLang.getGwtCode() + "\">");
            out.println("<script>\nvar messages = {");
            while ((line = br.readLine()) != null) {
                if (!line.startsWith("#") && line.contains("=")) {
                    if (count++ != 0) {
                        out.print("\",\n");
                    }
                    out.print(line.replace("=", ":\""));
                }
            }
            out.println("\"\n};\n</script>");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.doStartTag();
    }
}
